﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace PES.Common.Extensions
{
    public static class DbExtensions
    {
        /// <summary>
        /// Cria um comando pronto para ser executado no banco de dados.
        /// </summary>
        /// <remarks>Cria automaticamente os parâmetros internos via AddInParameter e mapeia os tipos
        /// dos argumentos passados diretamente para o DbType equivalente.</remarks>
        /// <param name="_db">Banco usado para gerar os comandos.</param>
        /// <param name="_queryFormat">Query SQL com os parâmetros a serem preenchidos.</param>
        /// <param name="_parameters">Parâmetros a serem populados na query.</param>
        /// <returns>Comando pronto para ser executado.</returns>
        public static DbCommand CreateCommand(this Database _db, string _queryFormat, params DbParam[] _parameters)
        {
            string[] dbParams = new List<string>(CreateDbParameters(_db, _parameters.Length)).ToArray();
            DbCommand cmd = _db.GetSqlStringCommand(String.Format(_queryFormat, dbParams));

            for (int i = 0; i < dbParams.Length; i++)
                _db.AddInParameter(cmd, dbParams[i], _parameters[i].DbType, _parameters[i].Data);

            return cmd;
        }

        private static IEnumerable<string> CreateDbParameters(Database _db, int _count)
        {
            for (int i = 0; i < _count; i++)
                yield return _db.BuildParameterName("param" + i);
        }

        public static long GetIdentityValue(this Database _db, DbTransaction _transaction, string _seqForOracle)
        {
            string sql = "";
            // Oracle
            if (_db is Microsoft.Practices.EnterpriseLibrary.Data.Oracle.OracleDatabase)
            {
                sql = "SELECT "+_seqForOracle+".currval as value FROM dual";
            }
            //SqlServer
            else
            {
                sql = "SELECT @@Identity as ObjID";
            }

            DbCommand cmd = _db.GetSqlStringCommand(sql);

            return Convert.ToInt64(_db.ExecuteScalar(cmd, _transaction));
        }
    }
}
